﻿using System;
using FormControllers;
using AgencyEntityLib.BaseEntity;
using System.Web.UI.WebControls;
using System.Collections.Generic;
using Ecopsy.Tools;
using Ecopsy.DataTier;
using System.Data;
using System.Data.SqlClient;


public partial class iFrameAdmin_EditEmploer : iAdmin_Page 
{
    
    private wsFace _ws_Face = (wsFace)GlobalConstants.CurrentAgency.WS_FactoryList[WS_FactoryList.wsKey_Face];

    
    private   string DepartmentID
    {
        get { return Request.QueryString[qDepartmentID]; }
    }
    
    private  string EmployerID
    {
        get { return Request.QueryString["EmployerID"]; }
    }

    private List<string> SelectedPermissionNodes = new List<string>();

    private void ReadForm()
    {
        SelectedPermissionNodes = new List<string>();
        Employeer.FirstName = txtFirstName.Text;
        Employeer.SecondName = txtSecondName.Text;
        Employeer.LastName = txtLastName.Text;
        Employeer.Position = txtPosition.Text;
        Employeer.eMail  = txtEmail.Text;
        Employeer.Describe = txtComment.Text;
        
        
        //// считать дерево с разрещениями  
        if (trPermissions.Nodes.Count > 0)
        {   
            ReadPermissionTree(trPermissions.Nodes[0]);
            SetPermission(SelectedPermissionNodes); 
        }
        // Установить роли товарища
        if (Employeer.Login.Length == 0) return;
        System.Web.Security.MembershipUser usr = System.Web.Security.Membership.GetUser(Employeer.Login);
        SetRoles(usr);
    }

    private void SetRoles(System.Web.Security.MembershipUser usr)
    {           
        foreach (ListItem item in chRoleList.Items)
        {
            List<string> AddRoleList = GetAddRoleList(item.Value);
           System.Web.Security.Roles.RemoveUserFromRole(usr.UserName, item.Value);
            foreach (string s in AddRoleList)
            {
                System.Web.Security.Roles.RemoveUserFromRole(usr.UserName, s);
            }
            
            if (item.Selected)
            {
                System.Web.Security.Roles.AddUserToRole(usr.UserName, item.Value);
                foreach (string s in AddRoleList)
                {
                    System.Web.Security.Roles.AddUserToRole(usr.UserName, s);
                }
            }

        }        
    }

    private void RemoveRole(string sRolename)
    { 
        
        
    }

    private void AddRole(string sRolename)
    {
    }

    /// <summary>
    /// Возвращает спсиок связанных сиситемных ролей с ролью приложения.
    /// </summary>
    /// <param name="sRolename"></param>
    /// <returns></returns>
    private List<string> GetAddRoleList(string sRolename)
    { 
        List<string> res= new List<string> ();        
        SqlTools t = new SqlTools(AppContext.GetSC());
        DataSet DS = t.ExecuteSql("select * from vAppRoleLink where AppRole='" + sRolename + "'");
        
        if (DS.Tables.Count == 0)
            return res;

        foreach (DataRow rw in DS.Tables[0].Rows)
        { 
            res.Add (rw[1].ToString ()); 
        }

        return res;
    }


    private void ReadPermissionTree(TreeNode nd)
    {
        string id=CmdStringEnv.GetParam(nd.DataPath, "ID");
        if (nd.Checked) SelectedPermissionNodes.Add(id);
        foreach (TreeNode c_nd in nd.ChildNodes)
        {
            ReadPermissionTree(c_nd);
        }

    }

    /// <summary>
    /// Редактируем текущего пользователя?
    /// </summary>
    public bool IsCurrentUser
    {
        get { return GlobalConstants.CurrentEmployeer.ID == Employeer.ID; }
    }
    

    /// <summary>
    /// Возвращает listItem с писок ролей с отметкой участия 
    /// </summary>
    /// <returns></returns>
    private ListItemCollection GetEmplRoles()
    {
        Employeer emp = Employeer;

        ////список ролей
        ws_Securety sc = new ws_Securety();
        RoleList r = sc.GetRoleList();
        

        RoleMemberList memb = sc.GetRoleMemberList(emp.Login);

        ListItemCollection coll = new ListItemCollection();

        foreach (DictionaryItem item in r)
        {
            ListItem i = new ListItem();
            i.Value = item.ID;
            i.Text = item.Value.ToString();
            i.Selected = (null != memb[item.ID]);
            coll.Add(i);
        }
        return coll;
    }

    #region Protected
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack) MyBind();
        Init();
    }

    private void MyBind()
    {
        if (!IsNewRecord)
        {
            trPermissions.DataSource = GetTreeSource();
        }
        lvLogin.DataSource = EmploeerAsList;

        ///chRoleList.DataSource = GetEmplRoles();////Чудо блять!!!
        ListItemCollection coll = GetEmplRoles();
        chRoleList.Items.Clear();
        foreach (ListItem i in coll)
        {
            ListItem it = new ListItem(i.Text, i.Value);
            it.Selected = i.Selected;
            chRoleList.Items.Add(it);
        }

        DataBind();
        if (!IsPostBack) trPermissions.CollapseAll();
    }

    private void Init()
    {   
        // проставить статус редактирования
        SetAlertForTextBox(this.Controls,"TextBox","onChange", "ShowAlert()");
        SetAlertForTextBox(this.Controls, "CheckBox", "onClick", "ShowAlert()");
        SetMsg_EditStatus();
    }
   
    protected Employeer Employeer
    {
        get 
        {        
            if (EmployerID.IndexOf(GlobalConstants.qPrefNEW_RECORD) > -1)//режим вставки?
            {
                return _ws_Face.GetNewEmpl(EmployerID);  
            }            
            return (Employeer) _ws_Face.GetEmpl(EmployerID); 
    
            //return _wsAgency.GetEmployer(DepartmentID, EmployerID); 
        }
    }

    protected List<Employeer> EmploeerAsList
    {
        get
        {
            List<Employeer> l = new List<Employeer>();
            l.Add(Employeer);
            return l;
        }
    }

    protected void btnsave_Click(object sender, EventArgs e)
    {
        ReadForm();
        Employeer emp = Employeer;
        if (emp.ID.IndexOf(GlobalConstants.qPrefNEW_RECORD) > -1)//режим вставки?
        {
            string s = emp.ID;
            emp.ID = emp.ID.Replace(GlobalConstants.qPrefNEW_RECORD, "");
            emp.DepartmentId = DepartmentID; 
            //сбросить нового сотрудника из кэша
            CacheTools.ResetCache(s);
            _ws_Face.SaveFace(emp);

            string sUrl="iFrameAdmin_EditEmployeer";
            bool isEnabled =false;
            iPageController.SetPageUrl (ref sUrl, ref isEnabled );  
            Response.Redirect(sUrl +".aspx?"+qDepartmentID +"="+DepartmentID +"&"+ qEmployerID +"="+ emp.ID  );
        }

        _ws_Face.SaveFace(emp);
        lblClientStatus.CssClass = GlobalConstants.cssHidden;
        //SetMsg_EditStatus();
        
    }

    protected void btnReturn_Click(object sender, EventArgs e)
    {   
        Response.Redirect("iFrameAdmin_Employees.aspx?" +qDepartmentID+"=" + DepartmentID);  

    }

    /// <summary>
    /// Работаем в режиме вставки?
    /// </summary>
    protected  bool IsNewRecord 
    {
        get { return Employeer.ID.IndexOf(GlobalConstants.qPrefNEW_RECORD) > -1; }
    }
    
    /// <summary>
    /// Вызвать диалог разрешений 
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnChangePermission_Click(object sender, EventArgs e)
    {   
        
    }    
    
    protected void trPermissions_TreeNodeDataBound(object sender, TreeNodeEventArgs e)
    {
        string s =CmdStringEnv.GetParam(e.Node.DataPath, "Selected");
        e.Node.Checked = s.Equals("True");
    }
    
    protected void btnChangeLogin_Click(object sender, EventArgs e)
    {
        if (hfLoginValue.Value != string.Empty && hfLoginValue.Value.IndexOf("unde") == -1)
        {
            Employeer.Login = hfLoginValue.Value;
            btnsave_Click(null, null); 
            
        }
    }

    protected string sOnChangeBtnClick
    {
        get
        {   
            return "var r= CallModalWindow('iFrameAdmin_Login.aspx?"+qLogin+ "="+Employeer.Login + "','200','500'); document.getElementById('ctl00_cphBody_hfLoginValue').innerText=r; ";    
        }
    }

    /// <summary>
    /// Флаг видимости 
    /// </summary>
    protected bool IsLoginVisible
    {
        get { return (Employeer.Login.Length != 0) ;}

    }

    #endregion

    
    #region Permissions
    
    private void AddPermission(string Perm_AgencyID)
    {
            Employeer empl = Employeer;
            if (null == empl.Permission[Perm_AgencyID])
            {
                DictionaryItem d = new DictionaryItem();
                d.ID = Perm_AgencyID;
                d.Value = Perm_AgencyID;
                empl.Permission.Add(d);
            }
    }

    private void RemovePermission(string Perm_AgencyID)
    {
        Employeer empl = Employeer;

        if (null != empl.Permission[Perm_AgencyID])
        {
            DictionaryItem d = (DictionaryItem)empl.Permission[Perm_AgencyID];
            empl.Permission.Remove(d);
        }
    }

    private  void SetPermission(List<string> ListAgencyPermission)
    {
        Employeer empl = Employeer;
        empl.Permission.Clear();
        foreach (string item in ListAgencyPermission)
        {
            DictionaryItem it = new DictionaryItem();
            it.ID = item;
            it.Value = item;
            empl.Permission.Add(it);
       }
    }
    
    #endregion

    /// <summary>
    /// соббщение о состоянии записи
    /// </summary>
    protected void SetMsg_EditStatus()
    {
        lblClientStatus.DataBind();
        updStatus.Update();
    }
    
    // Пказать скрыть предупрежденеие о несохраненных данных    
    protected string GetStateVisible()
    {        
        if (EmployerID.IndexOf(GlobalConstants.qPrefNEW_RECORD) > -1) return string.Empty;
        if (Employeer.State != EntityState.Loaded) return string.Empty;
        return "hidden";
    }

    private bool UpdateLogin(ListViewDataItem sender)
    {
        Ctl_ctlLoginEditor editor = (Ctl_ctlLoginEditor)sender.FindControl("ctlLoginEditor1");        
        List<string> res=editor.Save();
        if (res.Count > 0)
        {   
            _LoginErrMsg = res[0];            
            return false;
        }        

        return res.Count == 0;
    }
    private string _LoginErrMsg= string.Empty   ;
    public string LoginErrMsg { get 
    { 
        return _LoginErrMsg; 
    } 
    }

 
    Func<ListViewDataItem, bool> LvUpdCmd; 
    protected void ItemCommand(object sender, ListViewCommandEventArgs e)
    {
        if (string.Empty == e.CommandName) return;

        ListView lv = (ListView)sender;

        switch (lv.ID)
        {
            case "lvLogin":
                LvUpdCmd = UpdateLogin ;                     
                break;

        }

        switch (e.CommandName)
        {
            case "Edit":
                {

                    ListViewDataItem d = (ListViewDataItem)e.Item;
                    lv.EditIndex = d.DataItemIndex;

                    break;
                }
            case "Insert":
                {

                    break;
                }
            case "Update":
                {
                    if (LvUpdCmd((ListViewDataItem)e.Item)) 
                        lv.EditIndex = -1;                    
                        

                    break;
                }
            case "Delete":
                {
                    //DeleteCustomer(e.CommandArgument as string);
                    break;
                }

            case "Cancel":
                {
                    
                    break;
                }
        }

        switch (lv.ID)
        {
        //    case "lvContactFaces":
        //        lv.DataSource = ContactWorkers;
        //        break;
        //    case "lvTask":
        //        lv.DataSource = GetClientTasks(null);
        //        break;
            default:
                lv.DataSource = EmploeerAsList ;
                break;
        }
        lv.DataBind();
        chRoleList.DataBind();
        updLoginInfo.Update();
        SetAlertForTextBox(this.Controls, "TextBox", "onChange", "ShowAlert()");
        SetMsg_EditStatus();



    }

    #region Источник - дерево разрешений сотрудника

    /// <summary>
    /// Источник для списка разрешений сотрудника 
    /// </summary>
    #region Источник для дерева  Agency_TreeDataSource

    private F_TreeDataSource GetTreeSource()
    {
        ///Получить дерево департаментов
        wsAgency ws = new wsAgency();
        Agency a = ws.GetAgency();
        TreeEntitySingle tree = (TreeEntitySingle)a.Department;


        // определить делегат поставляющий класс определяющий формат ноды в дереве
        Func<TreeEntitySingle, F_TreeDataSource.F_TreeDataSourceView.F_TreeHierarchyData> f = delegate(TreeEntitySingle _tr)
        {
            return (AgencyPermissionNodeItemFormatter)new AgencyPermissionNodeItemFormatter(_tr,DepartmentID,EmployerID);
        };

        // вернуть древовидныйисточник данных
        return new F_TreeDataSource(tree, f);
    }

    public class AgencyPermissionNodeItemFormatter : F_TreeDataSource.F_TreeDataSourceView.F_TreeHierarchyData
    {
        private string _DepartmentID, _EmployerID;

        public AgencyPermissionNodeItemFormatter(TreeEntitySingle obj, string DepartmentID, string EmployerID) : base(obj) 
        {
            _DepartmentID = DepartmentID;
            _EmployerID = EmployerID;
        }

        public override bool HasChildren
        {
            get
            {
                return true;
            }
        }

        public override F_TreeDataSource.F_TreeDataSourceView.F_TreeHierarchyData GetNewObj(TreeEntitySingle nd)
        {
            return new AgencyPermissionNodeItemFormatter(nd,_DepartmentID,_EmployerID);
        }
        public override string ToString()
        {
            Department a = (Department)_nd;
            return a.Name;            
        }
        public override string Path
        {
            get
            {

                wsFace ws = (wsFace)GlobalConstants.CurrentAgency.WS_FactoryList[WS_FactoryList.wsKey_Face];
                Employeer empl =(Employeer)ws.GetFace(_EmployerID);
                Department a = (Department)_nd;
                string id = a.ID;
                if (null != empl.Permission[id])
                {
                    return "ID=" + a.ID + ",Selected=True";
                }
                else
                {
                    return "ID=" + a.ID + ",Selected=False";
                }
            }
        }
        public override object Item
        {
            get
            {
                return _nd;
            }
        }


    }
    
    

    #endregion

    #endregion


    protected void lvLogin_ItemEditing(object sender, ListViewEditEventArgs e)
    {

    }
    protected void lvLogin_ItemUpdating(object sender, ListViewUpdateEventArgs e)
    {

    }
    protected void lvLogin_ItemCanceling(object sender, ListViewCancelEventArgs e)
    {
        ((ListView)sender).EditIndex = -1;
        ((ListView)sender).DataSource = EmploeerAsList;
        ((ListView)sender).DataBind();
    }
}
